package com.diandi.messages.controller.email;

import com.diandi.messages.enums.ReturnCode;
import com.diandi.messages.properties.MessagePlatformProperties;
import com.diandi.messages.service.email.MessageEmailService;
import com.diandi.messages.sign.SignUtil;
import com.diandi.messages.tools.Tools;
import com.diandi.messages.utils.http.CheckParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by mxp on 2017/9/22.
 */
@Controller
@RequestMapping(value = "/email")
public class MessageEmailController {

    @Autowired
    private MessageEmailService emailService;

    @Autowired
    private MessagePlatformProperties messagePlatformProperties;

    @RequestMapping(value = "/send")
    @ResponseBody
    public String sendEmail(HttpServletRequest request){
        Map<String, String> returnMap = new HashMap<String, String>();
        Map<String, String> paramMap = Tools.getParameterMap(request, false);
        returnMap = CheckParams.checkParamsIsExist(paramMap, "toAddress", "subject", "content", "passCode", "merchantNo", "sign");
        if (!returnMap.isEmpty()){
            return Tools.createLinkString(returnMap, true);
        }
        returnMap = emailService.sendEmail(request);
        try {
            String sign = SignUtil.signRSA(returnMap, messagePlatformProperties.getPayPrivateSign(paramMap.get("merchantNo")), messagePlatformProperties.getCharset());
            returnMap.put("sign", sign);
        } catch (Exception e) {
            e.printStackTrace();
            returnMap = Tools.createReturnParams(ReturnCode.err, "", "");
        }

        return Tools.createLinkString(returnMap, true);
    }
}